//
//  ZZLineChart.m
//  折线图
//
//  Created by rimi on 16/3/15.
//  Copyright © 2016年 Zhangzhen. All rights reserved.
//

#import "ZZLineChart.h"
#import "ChartViewController.h"
#import "FitOfScreen.h"
/** 坐标轴信息区域宽度 */
static const CGFloat kPadding = 10.0;
/** 坐标系中横线的宽度 */
//static const CGFloat kCoordinateLineWith = 1.0;
@interface ZZLineChart ()

/** X轴的单位长度 */
@property (nonatomic, assign) CGFloat xAxisSpacing;
/** Y轴的单位长度 */
@property (nonatomic, assign) CGFloat yAxisSpacing;
/** X轴的信息 */
@property (nonatomic, strong) NSMutableArray<NSString *> *xAxisInformationArray;
/** Y轴的信息 */
@property (nonatomic, strong) NSMutableArray<NSString *> *yAxisInformationArray;
/** 颜色数组 */
@property (nonatomic, strong) NSMutableArray *gradientLayerColors;
/** 折线图终点处的标签 */
@property (nonatomic, strong) UIButton *tapButton;
@property (nonatomic, strong) NSMutableArray <UILabel *> * labels;

@end

@implementation ZZLineChart

- (NSMutableArray<UILabel *> *)labels {
    if (!_labels) {
        _labels = [[NSMutableArray alloc] init];
    }
    return _labels;
}
- (NSMutableArray *)temperature{
    if (!_temperature) {
        _temperature = [NSMutableArray array];

    }
    return _temperature;
}
- (CGFloat)xAxisSpacing {
    if (_xAxisSpacing == 0) {
        _xAxisSpacing = (self.bounds.size.width - kPadding) / (float)self.xAxisInformationArray.count;
    }
    return _xAxisSpacing;
}
- (CGFloat)yAxisSpacing {
    if (_yAxisSpacing == 0) {
        _yAxisSpacing = (self.bounds.size.height - kPadding) / (float)self.yAxisInformationArray.count;
    }
    return _yAxisSpacing;
}
- (NSMutableArray<NSString *> *)xAxisInformationArray {
    if (_xAxisInformationArray == nil) {
        // 创建可变数组
        _xAxisInformationArray = [[NSMutableArray alloc] init];
        // 当前日期和日历
        NSDate *today = [NSDate date];
        NSCalendar *currentCalendar = [NSCalendar currentCalendar];
        // 设置日期格式
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"MM/dd";
        // 获取最近一周的日期
        NSDateComponents *components = [[NSDateComponents alloc] init];
        for (int i = 0; i< 5; i++) {
            components.day = i;
            NSDate *dayOfLatestWeek = [currentCalendar dateByAddingComponents:components toDate:today options:0];
            NSString *dateString = [dateFormatter stringFromDate:dayOfLatestWeek];
            [_xAxisInformationArray addObject:dateString];
        }
    }
    return _xAxisInformationArray;
}
- (NSMutableArray *)DetailsWeather{
    if (!_DetailsWeather) {
        _DetailsWeather = [NSMutableArray array];

    }
    return _DetailsWeather;
}
- (NSMutableArray<NSString *> *)yAxisInformationArray {
    if (_yAxisInformationArray == nil) {
        _yAxisInformationArray = [NSMutableArray arrayWithObjects:@"0", @"10", @"20", @"30", @"40", @"50", nil];
    }
    return _yAxisInformationArray;
}
- (void)reloadData {
    [self setupLineChartLayerAppearance];
    [self startDrawlineChart];
}
// 折线图上的点（重写get方法，后期需要暴露接口）
- (NSMutableArray<ZZLineChartPoint *> *)pointArray {
    if (_pointArray == nil) {
        _pointArray = [NSMutableArray array];
    }
    return _pointArray;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // 设置折线图的背景色
        self.backgroundColor = [UIColor clearColor];
        /** 将折线添加到折线图层上，并设置相关的属性 */
        self.lineChartLayer = [CAShapeLayer layer];
        self.lineChartLayer.strokeColor = [UIColor whiteColor].CGColor;
        self.lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
        // 默认设置路径宽度为0，使其在起始状态下不显示
        self.lineChartLayer.lineWidth = 0;
        self.lineChartLayer.lineCap = kCALineCapRound;
        self.lineChartLayer.lineJoin = kCALineJoinRound;
        // 设置折线图层为渐变图层的mask
        [self.layer addSublayer:self.lineChartLayer];
    }
    return self;
}
- (NSMutableArray *)arrayLinePointArray:(NSMutableArray *)arrayPoint{
    NSMutableArray *array = [NSMutableArray arrayWithObjects:[ZZLineChartPoint pointWithX:1 andY:[arrayPoint[0] doubleValue]], [ZZLineChartPoint pointWithX:2 andY:[arrayPoint[1] doubleValue]], [ZZLineChartPoint pointWithX:3 andY:[arrayPoint[2] doubleValue]], [ZZLineChartPoint pointWithX:4 andY:[arrayPoint[3] doubleValue]], [ZZLineChartPoint pointWithX:5 andY:[arrayPoint[4] doubleValue]],  nil];
    return array;
}
- (void)drawRect:(CGRect)rect {
    [self.xAxisInformationArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIFont *informationFont = [UIFont fontWithName:@"FZHTK--GBK1-0" size:12*LRLRadioWidth];
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[NSForegroundColorAttributeName] = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0];
        attributes[NSFontAttributeName] = informationFont;
        CGSize informationSize = [obj sizeWithAttributes:attributes];
        // 计算绘制起点
        float drawStartPointX = idx * self.xAxisSpacing + (self.xAxisSpacing - informationSize.width) * 0.5 ;
        float drawStartPointY = 20;
        CGPoint drawStartPoint = CGPointMake(drawStartPointX+5, drawStartPointY);
        [obj drawAtPoint:drawStartPoint withAttributes:attributes];
    }];
}
- (void)setupLineChartLayerAppearance {
    /** 折线路径 */
    UIBezierPath *path = [UIBezierPath bezierPath];
    [self.pointArray enumerateObjectsUsingBlock:^(ZZLineChartPoint * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 折线
        if (idx == 0) {
            [path moveToPoint:CGPointMake(self.xAxisSpacing * 0.5 + (obj.x - 1) * self.xAxisSpacing, self.bounds.size.height - kPadding - obj.y * self.yAxisSpacing)];
        } else {
            [path addLineToPoint:CGPointMake(self.xAxisSpacing * 0.5 + (obj.x - 1) * self.xAxisSpacing, self.bounds.size.height - kPadding - obj.y * self.yAxisSpacing)];
        }
        [path addArcWithCenter:CGPointMake(self.xAxisSpacing * 0.5 + (obj.x - 1) * self.xAxisSpacing, self.bounds.size.height - kPadding - obj.y * self.yAxisSpacing) radius:2.0 startAngle:0 endAngle:2 * M_PI clockwise:YES];
    }];
    self.lineChartLayer.path = path.CGPath;
    // 设置动画的相关属性
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 2;
    pathAnimation.repeatCount = 1;
    pathAnimation.removedOnCompletion = NO;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    // 设置动画代理，动画结束时添加一个标签，显示折线终点的信息
    [self.lineChartLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}
/** 动画开始，绘制折线图 */
- (void)startDrawlineChart {
    for (UILabel * obj in self.labels) {
        [obj removeFromSuperview];
    }
    [self.labels removeAllObjects];
    // 设置路径宽度为4，使其能够显示出来
    self.lineChartLayer.lineWidth = 1;
    for (id obj in self.subviews) {
        if ([obj isKindOfClass:[UILabel class]]) { [(UILabel *)obj removeFromSuperview]; }
    }
    for (int idx = 0; idx < self.pointArray.count; ++ idx) {
        ZZLineChartPoint * obj = self.pointArray[idx];
        //温度标签
        UILabel *laber = [[UILabel alloc]init];
        laber.frame = CGRectMake((self.xAxisSpacing * 0.5 + (obj.x - 1) * self.xAxisSpacing)-6, (self.bounds.size.height - kPadding - obj.y * self.yAxisSpacing)+1, 30, 20);
        laber.text = self.temperature[idx];
        laber.textColor = [UIColor whiteColor];
        laber.font = [UIFont fontWithName:@"FZHTK--GBK1-0" size:13];
        laber.textAlignment = NSTextAlignmentCenter;
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animation.duration = 1.5;
        animation.autoreverses = NO;
        animation.fromValue = [NSNumber numberWithFloat:0.0];
        animation.toValue = [NSNumber numberWithFloat:1.0];
        animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeForwards;
        animation.delegate = self;
        [laber.layer addAnimation:animation forKey:@"transform.scale"];
        [self addSubview:laber];
        //天气详情标签
        UILabel *laber2 = [[UILabel alloc]init];
        laber2.frame = CGRectMake((self.xAxisSpacing * 0.5 + (obj.x - 1) * self.xAxisSpacing)-12, (self.bounds.size.height - kPadding - obj.y * self.yAxisSpacing)+13, 30, 20);
        laber2.text = self.DetailsWeather[idx];
        laber2.textColor = [UIColor whiteColor];
        laber2.font = [UIFont fontWithName:@"FZHTK--GBK1-0" size:14];
        laber2.textAlignment = NSTextAlignmentCenter;
        CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animation2.duration = 0.7;
        animation2.autoreverses = NO;
        animation2.fromValue = [NSNumber numberWithFloat:0.0];
        animation2.toValue = [NSNumber numberWithFloat:1.0];
        animation2.removedOnCompletion = NO;
        animation2.fillMode = kCAFillModeForwards;
        animation2.delegate = self;
        [laber2.layer addAnimation:animation2 forKey:@"transform.scale"];
        [self addSubview:laber2];
        [self.labels addObject:laber];
        [self.labels addObject:laber2];
    }
}

@end
